package xju.rjxy.shop.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC工具类
 */
public class JDBCUtils {
    /**
     * 数据源
     */
    private static DataSource dataSource;

    /**
     * 同一个线程共享的数据库连接
     */
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /**
     * 初始化数据源及数据库连接池
     */
    static {
        try {
            System.out.println("[JDBCUtils] 静态代码块开始");
            Properties properties = new Properties();
            InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            if (inputStream == null) {
                System.err.println("==== db.properties not found! ====");
                throw new RuntimeException("db.properties not found!");
            }
            System.out.println("[JDBCUtils] db.properties 文件已找到");
            properties.load(inputStream);
            System.out.println("[JDBCUtils] db.properties 加载完成");
            // 打印所有配置项
            for (String key : properties.stringPropertyNames()) {
                System.out.println("[JDBCUtils] 配置项: " + key + " = " + properties.getProperty(key));
            }
            // 创建DataSource
            dataSource = DruidDataSourceFactory.createDataSource(properties);
            System.out.println("[JDBCUtils] Druid DataSource 创建成功");
        } catch (IOException e) {
            System.err.println("[JDBCUtils] IOException: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (Exception e) {
            System.err.println("[JDBCUtils] Exception: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() {
        // 先从ThreadLocal获取数据库连接
        Connection connection = threadLocal.get();

        // 如果从ThreadLocal没有获取到connection，就从连接池获取
        if (connection == null) {
            try {
                connection = dataSource.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        return connection;
    }

    /**
     * 释放数据库连接
     */
    public static void close() {
        // 先从ThreadLocal获取数据库连接
        Connection connection = threadLocal.get();

        // 获取的connection不为null才进行释放
        if (connection != null) {
            // 从ThreadLocal移除
            threadLocal.remove();
            try {
                // 释放连接（这里是回收到Druid连接池）
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
